package com.demo;

import java.io.File;
import java.util.Random;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.SortedNumericSortField;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**排序
 * @author Ziroom
 *
 */
public class DemoSort {

	private static final String PATH = "d:\\zsl\\index15";

	public static void createIndexSort() throws Exception {
        //1、创建一个Director对象，指定索引库保存的位置。

        //1.1把索引库保存在内存中
        //Directory directory = new RAMDirectory();

        //1.2把索引库保存在磁盘
        Directory directory = FSDirectory.open(new File(PATH).toPath());

        //2、基于Directory对象创建一个IndexWriter对象
        IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        //当使用IKAnalyzer分词时，是如下写法。
       	//IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        IndexWriter indexWriter = new IndexWriter(directory, config);

        Random _r = new Random();
        for (int i=0; i<5000; i++) {
            //取文件名
            String fileName = "测试文件" + i;

            Field fieldName = new StringField("name", fileName, Field.Store.YES);

            //创建文档对象
            Document document = new Document();
            //向文档对象中添加域
            document.add(fieldName);
            if(i != 1024) {
            	if(i == 202 || i == 303 || i == 404) {
            		document.add(new StringField("pubmonth", String.valueOf(12), Field.Store.YES));  
            		document.add(new NumericDocValuesField("pubmonth", 12));
            	} else {
            		int id = _r.nextInt(100000);
            		document.add(new StringField("pubmonth", String.valueOf(id), Field.Store.YES));  
            		document.add(new NumericDocValuesField("pubmonth", id));
            	}
            	int id = _r.nextInt(100000);
            	document.add(new StringField("number", "No" + id, Field.Store.YES));  
            	document.add(new SortedDocValuesField("number", new BytesRef("No" + id)));
            }
            //5、把文档对象写入索引库
            System.out.println(indexWriter.addDocument(document));

        }
        //6、关闭indexwriter对象
        indexWriter.close();
    }

	public static void searchIndexSort() throws Exception {
        //1、创建一个Director对象，指定索引库的位置
        Directory directory = FSDirectory.open(new File(PATH).toPath());
        //2、创建一个IndexReader对象
        IndexReader indexReader = DirectoryReader.open(directory);
        //3、创建一个IndexSearcher对象，构造方法中的参数indexReader对象。
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        Sort sort = new Sort(new SortField("pubmonth", SortedNumericSortField.Type.INT), 
        		new SortField("number", SortField.Type.STRING, true));
        long s = System.currentTimeMillis();
        TopDocs topDocs = indexSearcher.search(new MatchAllDocsQuery(), 7, sort);
        //6、取查询结果的总记录数
        System.out.println("查询总记录数：" + topDocs.totalHits);
        //7、取文档列表
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        //8、打印文档中的内容
        for (ScoreDoc doc : scoreDocs) {
            //取文档id
            int docId = doc.doc;
            //根据id取文档对象
            Document document = indexSearcher.doc(docId);
            System.out.println(docId);
            System.out.println(document.get("name"));
            System.out.println(document.get("pubmonth"));
            System.out.println(document.get("number"));

        }
        long e = System.currentTimeMillis();
        System.out.println("time: " + (e-s));
        //9、关闭IndexReader对象
        indexReader.close();
    }

	public static void main(String[] args) throws Exception {
		//createIndexSort();
		searchIndexSort();
	}

}
